package com.example.oj_springboot.service;

import com.example.oj_springboot.config.NullException;
import com.example.oj_springboot.model.Answer;
import com.example.oj_springboot.model.Question;
import com.example.oj_springboot.component.Task;
import com.example.oj_springboot.mapper.ProblemMapper;
import com.example.oj_springboot.model.CompileRequest;
import com.example.oj_springboot.model.CompileResponse;
import com.example.oj_springboot.model.Problem;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

@Service
public class CompileService {

    @Resource
    private ProblemMapper problemMapper;

    public CompileResponse compile(CompileRequest compileRequest) throws Exception {
        //根据请求中的id查询数据库，并得到测试用例代码
        Problem problem =  problemMapper.getOne(compileRequest.getId());
        if(problem==null){
            throw new Exception();
        }
        String testCode = problem.getTestCode();

        //获取到用户提交的代码，并和测试代码进行拼接
        String requestCode = compileRequest.getCode();
        String finalCode = mergeCode(requestCode, testCode);
        if(finalCode==null||"".equals(finalCode)){
            throw new NullException();
        }

        //创建一个Task实例，调用complieAndRun方法来执行
        Task task = new Task();
        Question question = new Question();
        question.setCode(finalCode);
        Answer answer = task.compileAndRun(question);

        //5.把运行结果包装成一个HTTP响应并返回
        CompileResponse compileResponse = new CompileResponse();
        compileResponse.setError(answer.getError());
        compileResponse.setReason(answer.getReason());
        compileResponse.setStdout(answer.getStdout());

        return compileResponse;
    }


    private String mergeCode(String requestCode, String testCode) {
        //1.先从 requestCode 中找到末尾的 } , 并且截取出前面的代码
        int pos = requestCode.lastIndexOf("}");
        if (pos == -1) {
            return null;
        }
        //2.把 testCode 拼接到后面, 并再拼接上一个 } 就好了
        return requestCode.substring(0, pos) + testCode + "}";
    }
}
